package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");

        //通过ticket的信息，判断用户是否登陆，从而做出不同的处理
        if(ticket != null){ //用户有凭证
            //查询凭证，获取凭证对象，此处模拟查找指定用户session
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //检验凭证是否有效，有效才能进行其他操作
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                //凭证有效，根据凭证的userID查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                //在本次请求中持有用户,将信息存入到当前线程持有的map中
                // (因为浏览器和服务器的关系是多对一的，并发的，服务器创建多个线程进行处理，每个线程处理的信息不一样，因此需采用线程隔离)
                hostHolder.setUser(user);
            }


        }
        return true;
    }

    //在模版引擎之前存入相关数据
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //获取用户信息
        User user = hostHolder.getUser();
        //异常处理
        if(user != null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }

    //在整个请求结束之后，清楚用户信息
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
